package com.zhanghu.backendZray.serializer;

import com.zhanghu.backendZray.annotation.TypeChange;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@NoArgsConstructor
@AllArgsConstructor
public class TypeChangeSerialize extends BaseJKAnnotationSerializer<TypeChange, Byte> {

    private String[] annotationValues;

//    @Override
//    public void serialize(Byte value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
//            throws IOException {
//        String[] types = this.annotation.replace();
//        Map<String, String> typeMap = new ConcurrentHashMap<>();
//        if (Objects.nonNull(types) && types.length > 0) {
//            for (String type : types) {
//                String[] s = type.split("_");
//                typeMap.put(s[0],s[1]);
//            }
//        }
//        jsonGenerator.writeString(typeMap.get(String.valueOf(value)));
//    }


    @Override
    public void serialize(Byte value, JsonGenerator gen, SerializerProvider provider)
                                throws IOException {
        String[] types = this.annotationValues;
        Map<String, String> typeMap = new ConcurrentHashMap<>();
        if (Objects.nonNull(types) && types.length > 0) {
            for (String type : types) {
                String[] s = type.split("_");
                typeMap.put(s[0],s[1]);
            }
        }
        gen.writeString(typeMap.get(String.valueOf(value)));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider,
                            BeanProperty property) throws JsonMappingException {
        if (Objects.isNull(property)){
            return provider.findNullValueSerializer(null);
        }
        //校验当前bean是否为String或Byte
        if (Objects.equals(property.getType().getRawClass(),String.class) ||
                Objects.equals(property.getType().getRawClass(),Byte.class)){
            TypeChange typeChange = property.getAnnotation(TypeChange.class);
            if (Objects.isNull(typeChange)){
                typeChange = property.getContextAnnotation(TypeChange.class);
            }
            if (Objects.nonNull(typeChange)){
                return new TypeChangeSerialize(typeChange.replace());
            }
        }
        return provider.findValueSerializer(property.getType(), property);
    }
}